package com.gxg.controller;

import com.gxg.dockerapi.DockerContainerAPI;
import com.gxg.entities.User;
import com.gxg.services.ContainerService;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DockerController
{
  @Value("教师")
  private String adminRole;
  @Value("http://192.168.2.36:2375")
  private String dockerServerIp;
  @Autowired
  ContainerService containerService;
  
  @GetMapping({"/get_container_information"})
  @ResponseBody
  public String getContainerInformation(HttpServletRequest request)
    throws IOException
  {
    HttpSession session = request.getSession();
    if (session.getAttribute("user") != null)
    {
      User user = (User)session.getAttribute("user");
      session.setAttribute("user", user);
      if (this.adminRole.equals(user.getRole())) {
        return DockerContainerAPI.queryContainersInfo(this.dockerServerIp);
      }
      return "error:没有权限";
    }
    return "error:请先登录";
  }
  
  @PostMapping({"/get_container_id"})
  @ResponseBody
  public String getContainerId(@RequestParam("documentId") String documentId, HttpServletRequest request)
    throws IOException
  {
    HttpSession session = request.getSession();
    if (session.getAttribute("user") != null)
    {
      User user = (User)session.getAttribute("user");
      session.setAttribute("user", user);
      if (this.adminRole.equals(user.getRole())) {
        return this.containerService.getContainerId(documentId);
      }
      return "error:没有权限";
    }
    return "error:请先登录";
  }
  
  @PostMapping({"/remove_container"})
  @ResponseBody
  public String removeContainer(@RequestParam("containerId") String containerId, HttpServletRequest request)
    throws IOException
  {
    HttpSession session = request.getSession();
    if (session.getAttribute("user") != null)
    {
      User user = (User)session.getAttribute("user");
      session.setAttribute("user", user);
      if (this.adminRole.equals(user.getRole()))
      {
        int resCodeKill = DockerContainerAPI.killContainer(this.dockerServerIp, containerId);
        if (resCodeKill == 204)
        {
          int resCodeRemove = DockerContainerAPI.removeContainer(this.dockerServerIp, containerId);
          if (resCodeRemove == 204) {
            return "删除容器成功";
          }
          return "删除容器失败";
        }
        return "error:停止容器失败";
      }
      return "error:没有权限";
    }
    return "error:请先登录";
  }
}
